/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.unipar.cursoweb.service;

import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;

/**
 *
 * @author Thiago Marques
 */
public class GenericServiceImpl<T>
        implements GenericService<T> {

    @PersistenceContext
    protected EntityManager entityManager;
    private final Class<T> oClass;

    @Override
    public Connection getCon() {
        return ((Session) entityManager.getDelegate()).connection();
    }

    @SuppressWarnings("unchecked")
    public GenericServiceImpl() {
        this.oClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public T getById(Long id) {
        return entityManager.find(oClass, id);
    }

    @Override
    public T salvar(T t) {
        return entityManager.merge(t);
    }

    @Override
    public void excluir(T t) {
        entityManager.remove(entityManager.merge(t));
    }
}
